<template>
  <el-container>
    <el-main>
      <el-form ref="productForm" :model="form" label-width="90px">
        <div style="display: flex">
          <el-form-item
            label="菜品名称"
            prop="name"
            style="width: 600px"
            :rules="{
              required: true,
              message: '请输入商品名称',
              trigger: 'blur',
            }"
          >
            <el-input v-model="form.name" />
          </el-form-item>
        </div>
           <div style="display: flex">
          <el-form-item
            label="配送方式"
            prop="shippingMethod"
            style="width: 300px"
            :rules="{
              required: true,
              message: '请选择配送方式',
              trigger: 'blur',
            }"
          >
            <el-select
              v-model="form.shippingMethod"
              style="width: 100%"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="item in shippingMethodList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="运费模板" style="width: 300px">
            <!--可搜索带选择框-->
            <el-select
              v-model="form.freightId"
              style="width: 100%"
              clearable
              filterable
              placeholder="请选择运费键字"
              :filter-method="searchFreight"
              :loading="freightLoading"
              @change="freightChange"
            >
              <el-option
                v-for="item in freightNames"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <el-option
                style="background-color: #f9f9f9; text-align: center"
                label="--- 新增运费 ---"
                value="/"
              />
            </el-select>
          </el-form-item>
        </div>
        <div style="display: flex">
          <!-- <el-form-item label="菜品类型" prop="type" style="width: 300px" :rules="{ required: true, message: '请选择商品类型', trigger: 'blur' }">
            <el-cascader
              v-model="tempType"
              style="width: 100%;"
              :options="productTypeOptions"
              :props="{ expandTrigger: 'hover', value: 'id', label: 'name', children: 'childrens'}"
            />
          </el-form-item> -->
          <el-form-item
            label="菜品分类"
            prop="productCategoryId"
            style="width: 300px"
            :rules="{
              required: true,
              message: '请选择商品分类',
              trigger: 'change',
            }"
          >
            <el-input
              v-model="categoryName"
              suffix-icon="el-icon-arrow-down"
              @focus="dialogShow"
            />
          </el-form-item>
           <el-form-item label="商品标签" style="width: 300px">
          <el-select
            v-model="tagIds"
            style="width: 100%"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        </div>
        <!-- <div style="display: flex">
          <el-form-item label="菜品来源" style="width: 300px">
            <el-select v-model="form.publishType" placeholder="请选择" style="width:100%">
              <el-option label="自营" :value="0" />
              <el-option label="联营" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="主供应商" style="width: 300px" :rules="{ required: true, message: '请选择供应商', trigger: 'change' }" prop="supplierId">
            <el-select
              v-model="form.supplierId"
              style="width:100%"
              filterable
              placeholder="请选择供应商关键字"
              :filter-method="searchSupp"
              :loading="suppLoading"
              @change="suppChange"
            >
              <el-option
                v-for="item in suppOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增供应商 ---" value="#" />
            </el-select>
          </el-form-item>

        </div> -->


        <el-tabs>
          <!--tab1-->
          <el-tab-pane label="SKU">
            <!--             <div style="width: 100%;display: flex;justify-content: flex-end;align-items: center">-->
            <!--              <el-button type="primary" style="margin-bottom: 10px;" @click="addProduct" >添加规格</el-button>-->
            <!--            </div>-->
            <!--商品规格-->
            <el-row
              style="
                display: flex;
                justify-content: flex-end;
                position: relative;
                margin-left: 30px;
              "
            >
              <span
                class="el-icon-plus"
                style="
                  position: absolute;
                  left: 0px;
                  top: -25px;
                  color: #409eff;
                "
                @click="addProduct"
              />
              <el-col :span="23">
                <el-table :data="productList" border stripe style="width: 100%">
                  <el-table-column label="货号/条码" width="120">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.sn" />
                    </template>
                  </el-table-column>
                  <el-table-column label="商品图片" width="80" align="center">
                    <template slot-scope="{ row }">
                      <single-upload
                        v-model="row.thumbnail"
                        list-type="picture-card"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="规格" min-width="120">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.spec1" />
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="套餐形式" min-width="85">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.spec2" />
                    </template>
                  </el-table-column> -->
                  <el-table-column label="单位" width="70">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.unit" />
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="单位类型" width="110">
                    <template slot-scope="{ row }">
                      <el-select
                        v-model="row.unitType"
                        placeholder="请选择"
                        disabled
                        @change="chooseUnitType(row.length)"
                      >
                        <el-option label="不启用" :value="0" /> -->
                        <!-- :disabled="row.isClick" -->
                        <!-- <el-option label="最小单位" :value="1" :disabled="row.isClick" />
                        <el-option label="统计单位" :value="2" :disabled="row.isCount||row.isFirst" />
                        <el-option label="辅助单位" :value="3" :disabled="row.isFirst" /> -->
                      <!-- </el-select>
                    </template>
                  </el-table-column> -->
                  <!-- <el-table-column label="系数" width="80">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.unitRate" disabled />
                    </template>
                  </el-table-column> -->
                  <el-table-column label="库存" width="80">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.stock" type="number"   @mousewheel.native.prevent
                                @DOMMouseScroll.native.prevent/>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="积分"
                    width="85"
                    v-if="tempType == 12"
                  >
                    <template slot-scope="{ row }">
                      <el-input v-model="row.point" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column label="市场价" width="85">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.marketPrice" type="number"  @mousewheel.native.prevent
                      @DOMMouseScroll.native.prevent />
                    </template>
                  </el-table-column>
                  <el-table-column label="销售价" width="85">
                    <template slot-scope="{ row }">
                      <el-input v-model="row.price" type="number"   @mousewheel.native.prevent
                                @DOMMouseScroll.native.prevent/>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column
                    label="成本价"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.cost" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>0"
                    :label="vips[0].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip1price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>1"
                    :label="vips[1].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip2price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>2"
                    :label="vips[2].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip3price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>3"
                    :label="vips[3].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip4price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>4"
                    :label="vips[4].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip5price" type="number" />
                    </template>
                  </el-table-column> -->
                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template v-if="!row.isList" slot-scope="{ row }">
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="top-start"
                      >
                        <a @click="delProduct(row)">
                          <i style="color: #f56c6c" class="el-icon-delete" />
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!--tab2-->
          <el-tab-pane label="属性">
            <div style="display: flex">
              <el-form-item label="分销策略" style="width: 300px">
                <el-select
                  v-model="form.distributionId"
                  style="width: 100%"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in disOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="品牌类型" style="width: 300px">
                <!--可搜索带选择框-->
                <el-select
                  v-model="form.brandId"
                  style="width: 100%"
                  filterable
                  placeholder="请选择品牌关键字"
                  :filter-method="searchBrand"
                  :loading="brandLoading"
                  @change="brandChange"
                >
                  <el-option
                    v-for="item in barrelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                  <el-option
                    style="background-color: #f9f9f9; text-align: center"
                    label="--- 新增品牌 ---"
                    value="#"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div style="display: flex">
              <el-form-item label="最小订购量" style="width: 300px">
                <el-input
                  v-model="form.minLimit"
                  type="number"
                  @mousewheel.native.prevent
                />
              </el-form-item>
              <el-form-item label="最大日限量" style="width: 300px">
                <el-input v-model="form.maxLimit" type="number" />
              </el-form-item>
            </div>
            <div style="display: flex">
              <!-- <el-form-item label="运费模板" style="width: 300px">

                <el-select
                  v-model="form.freightId"
                  style="width: 100%"
                  clearable
                  filterable
                  placeholder="请选择运费键字"
                  :filter-method="searchFreight"
                  :loading="freightLoading"
                  @change="freightChange"
                >
                  <el-option
                    v-for="item in freightNames"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                  <el-option
                    style="background-color: #f9f9f9; text-align: center"
                    label="--- 新增运费 ---"
                    value="/"
                  />
                </el-select>
              </el-form-item> -->

                <el-form-item label="保质期(天)" style="width: 300px">
              <el-input
                v-model="form.quality"
                type="number"
                @mousewheel.native.prevent
              />
            </el-form-item>
              <el-form-item label="重量(Kg)" style="width: 300px">
                <el-input
                  v-model="form.weight"
                  type="number"
                  @mousewheel.native.prevent
                />
              </el-form-item>
            </div>

            <!--            <div>-->
            <!--              <el-form-item label="属性标签" style="width: 300px">-->
            <!--                <el-input v-model="article.productMeta.label" placeholder="例如:辛辣,微酸" />-->
            <!--              </el-form-item>-->
            <!--            </div>-->
            <div style="display: flex">
              <el-form-item label="菜品描述" style="width: 600px">
                <el-input
                  v-model="form.subTitle"
                  placeholder="在商品以副标题形式展示"
                />
              </el-form-item>
            </div>
          </el-tab-pane>
          <!--tab3-->
          <!-- <el-tab-pane label="清单">
            <el-row style="display: flex; justify-content: flex-end; position: relative;margin-left: 30px">
              <span class="el-icon-circle-plus-outline" style="position: absolute; left: 0px; top: 66px; color: #409EFF;" @click="addProps" />
              <el-col :span="23">
                <el-table
                  :data="article.productMeta.props"
                  border
                  stripe
                  style="width:600px;"
                >
                  <el-table-column
                    label="名称"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.name" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="说明"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.memo" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="参数"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.params" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template  slot-scope="scope" v-if="scope.$index!=0">
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <a @click="delProps(scope)">
                          <i style="color: #F56C6C" class="el-icon-delete" />
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>

            </el-row>
          </el-tab-pane> -->
          <el-tab-pane label="详情">
            <div class="menu-wrapper">
              <tinymce v-model="article.content" :height="300" :width="950" />
              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px">
                    <span style="font-size: 18px; color: #409eff">轮播图</span>
                  </div>
                </div>
                <el-col :span="15">
                  <multi-upload v-model="article.productMeta.images" />
                </el-col>
              </el-row>
              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px">
                    <span
                      style="font-size: 18px; color: #409eff; margin: 10px 0"
                      >视频介绍</span
                    >
                  </div>
                </div>
                <el-col :span="8">
                  <video-upload v-model="article.productMeta.video" />
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <el-button
            style="margin-top: 30px"
            type="primary"
            :loading="clicked"
            @click="saveProduct('productForm')"
          >
            &nbsp&nbsp完 成&nbsp&nbsp
          </el-button>
        </el-form-item>
      </el-form>
      <category-dialog
        ref="categoryDialog"
        request="productCategory"
        @confirm="categoryDialogConfirm"
      />
      <el-dialog
        v-el-drag-dialog
        title="添加品牌"
        :visible.sync="brandVisible"
        width="50%"
        :before-close="brandClose"
      >
        <div style="height: 70vh; overflow: auto; position: relative">
          <brandAdd :is-dialog="true" @confirm="brandAddConfirm" />
        </div>
      </el-dialog>

      <el-dialog
        v-el-drag-dialog
        title="添加供应商"
        :visible.sync="suppVisible"
        width="50%"
        :before-close="suppClose"
      >
        <div style="height: 70vh; overflow: auto; position: relative">
          <suppAdd :is-dialog="true" @confirm="suppAddConfirm" />
        </div>
      </el-dialog>

      <addFreight
        ref="freight"
        :is-dialog="true"
        @confirm="freightAddConfirm"
      />
    </el-main>
  </el-container>
</template>
<style lang="scss" scoped>
/deep/.el-input__inner {
  padding: 0 5px;
}
.photo-content {
  width: 100%;
  display: flex;
  align-items: flex-end;
  border-top: 1px #eee solid;
  margin-bottom: 20px;
  margin-top: 10px;
}
/deep/ .el-upload--picture-card {
  width: 50px !important;
  height: 50px !important;
  line-height: 50px !important;
  text-align: center;
}
</style>
<script>
import { list as vipList } from "@/api/vip";
import MultiUpload from "@/components/Upload/multiUpload";
import VideoUpload from "@/components/Upload/videoUpload";
import Tinymce from "@/components/Tinymce";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { EventBus } from "@/api/eventBus";
import utils from "../../utils/utils.js";
import { save } from "@/api/product";
import { save as saveInfo } from "@/api/productArticle";
import { list as tagList } from "@/api/tag";
import { list as brandList } from "@/api/brand";
import { list as suppList } from "@/api/supplier";
import CategoryDialog from "@/components/CategoryDialog";
import SingleUpload from "@/components/Upload/singleUpload";
import brandAdd from "../brand/add.vue";
import suppAdd from "../supplier/add.vue";
import { list as freightList } from "@/api/freight";
import addFreight from "../freight/add";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list as distributionList } from "@/api/distribution.js";
import { getMenuTree as MenuTree } from "@/api/sysMch";

export default {
  name: "product-add",
  directives: { elDragDialog, permission },
  filters: {},
  components: {
    CategoryDialog,
    SingleUpload,
    brandAdd,
    suppAdd,
    MultiUpload,
    VideoUpload,
    Tinymce,
    addFreight,
  },
  props: ["type"],
  data() {
    return {
      isCount: true,
      isShow: true,
      vips: [],
      clicked: false, // 按钮防双击
      categoryName: "",
      subscribe: false,
      market: false,
      shippingMethodList: [
        { name: "骑手配送", value: 2 },
        { name: "到店提货", value: 1 },
        { name: "全国快递", value: 0 },
      ],
      freightVisible: false,
      form: {
        maxLimit: "",
        publishType: 0,
        name: "",
        productCategoryId: "",
        shortName: "",
        orders: 0,
        type: "0",
        shippingMethod: "",
        isMarketable: false,
        subTitle: "",
        minLimit: "",
        freightId: "",
        quality: "",
        distributionId: "",
        brandId: "",
        supplierId: "",
        allocatedStock: "",
        weight: "",
      },
      article: {
        goods: "",
        productMeta: {
          // label: '',
          props: [{ name: "", memo: "", params: "" }],
          images: [],
          video: "",
        },
        content: "",
      },
      tagIds: [],
      length: 0,
      freightNames: [],
      disOptions: [],
      tagOptions: [],
      brandLoading: false,
      brandVisible: false,
      barrelOptions: [],
      suppOptions: [],
      tempType: 0,
      // tempType: [10, 20],
      // productTypeOptions: [
      //   {
      //     id: 10, name: '实物商品',
      //     childrens: [
      //       { id: 20, name: '普通商品' }
      //     ]
      //   },
      //   {
      //     id: 11, name: '虚拟商品',
      //     childrens: [
      //       { id: 20, name: '商品' },
      //       { id: 21, name: '套餐' }
      //     ]
      //   },
      //   {
      //     id: 12, name: '积分商品',
      //   }
      // ],
      freightLoading: false,
      suppLoading: false,
      suppVisible: false,
      productList: [
        {
          isClick: false,
          isFirst: true,
          maxLimit: "",
          publishType: 0,
          length: 0,
          isList: true,
          name: "",
          productCategoryId: "",
          shortName: "",
          orders: 0,
          type: "0",
          freightId: "",
          isMarketable: false,
          subTitle: "",
          minLimit: "",
          // labal: '',
          quality: "",
          isChose: false,
          isCount: false,
          distributionId: "",
          brandId: "",
          stock: "",
          supplierId: "",
          allocatedStock: "",
          weight: "",
          subType: 0,
          shippingMethod: "0",
          // ------
          sn: "",
          thumbnail: "",
          spec1: "",
          spec2: "",
          unit: "",
          unitRate: 1,
          marketPrice: "",
          price: "",
          cost: "",
          unitType: 0,
          vip1price: "",
          vip2price: "",
          vip3price: "",
          vip4price: "",
          vip5price: "",
          point: "",
          article: {
            productMeta: {
              images: [],
              props: [{ name: "", memo: "", params: "" }],
              video: "",
              // label: ''
            },
            content: "",
          },
        },
      ],
    };
  },
  created() {
    EventBus.$on("freight-add", (res) => {
      // 监听新增完毕
      // 更新列表数组
      this.freightNames.splice(0, 0, res);
    });
    this.loadMenuTree();
    this.loadVip();
    this.loadFright("");
    this.loadTag();
    this.loadDistribution();
    this.loadBrand("");
    this.loadSupp("");
  },
  methods: {
    loadMenuTree() {
      // 根据权限判断是否显示
      MenuTree()
        .then((res) => {
          res.data.forEach((list) => {
            if (list.permission == "product.list") {
              list.childrens.forEach((item) => {
                if (item.permission == "emptyBarrel-list") {
                  this.productTypeOptions[0].childrens.push({
                    id: 24,
                    name: "管理空桶",
                  });
                  this.productTypeOptions[1].childrens.push({
                    id: 23,
                    name: "押金",
                  });
                } else if (item.permission == "waterTicket-list") {
                  this.productTypeOptions[1].childrens.push({
                    id: 22,
                    name: "水票",
                  });
                }
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // chooseUnitType(data) {
    //   if (this.productList.length > 1 && this.productList[0].unitType === 1) {
    //     if (this.productList[data].unitType === 2) {
    //       for (var l = 1; l < this.productList.length; l++) {
    //         this.productList[l].isCount = true;
    //       }
    //       this.productList[data].isCount = false;
    //       console.log(this.productList);
    //     } else {
    //       for (var v = 1; v < this.productList.length; v++) {
    //         this.productList[v].isCount = false;
    //       }
    //     }
    //   }

    //   if (this.productList.length > 1) {
    //     if (this.productList[0].unitType == 0) {
    //       for (var i = 1; i < this.productList.length; i++) {
    //         this.productList[i].unitType = 0;
    //         this.productList[i].isChose = true;
    //       }
    //     } else {
    //       for (var i = 1; i < this.productList.length; i++) {
    //         this.productList[i].isChose = false;
    //       }
    //     }
    //   }
    // },
    loadDistribution() {
      distributionList()
        .then((res) => {
          this.disOptions = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    loadVip() {
      vipList().then((res) => {
        res.data.data.forEach((item) => {
          if (item.vip > 0) {
            this.vips.push(item);
          }
        });
        this.vips = this.vips.sort(this.compare("vip", true));
        console.log(this.vips);
      });
    },
    compare(property, desc) {
      return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        if (desc == true) {
          // 升序排列
          return value1 - value2;
        } else {
          // 降序排列
          return value2 - value1;
        }
      };
    },
    searchFreight(query) {
      if (query.length < 2) {
        this.$message.error("不得少于两个字符");
        return;
      }
      this.loadFright(query);
    },
    loadFright(query) {
      this.freightNames = [];
      const params = new URLSearchParams();
      params.append("name", query);
      params.append("pageNum", 1);
      params.append("pageSize", 1000);
      this.freightLoading = true;
      freightList(params)
        .then((response) => {
          this.freightLoading = false;
          this.freightNames = response.data.data;
        })
        .catch((error) => {
          this.freightLoading = false;
        });
    },
    loadTag() {
      const _this = this;
      const params = new URLSearchParams();
      params.append("pageNum", 1);
      params.append("pageSize", 20);
      params.append("type", 3);
      tagList(params)
        .then((response) => {
          console.log(response);
          _this.tagOptions = response.data.data;
        })
        .catch((error) => {});
    },
    dialogShow() {
      console.log("点击了");
      this.$refs.categoryDialog.show();
    },
    categoryDialogConfirm(val) {
      this.form.productCategoryId = val.id;
      this.categoryName = val.name;
    },
    loadBrand(query) {
      const params = new URLSearchParams();
      params.append("pageNum", 1);
      params.append("pageSize", 50);
      params.append("name", query);
      this.brandLoading = true;
      brandList(params)
        .then((response) => {
          console.log(response);
          this.brandLoading = false;
          this.barrelOptions = response.data.data;
        })
        .catch((error) => {
          this.brandLoading = false;
        });
    },
    searchBrand(query) {
      if (query.length < 2) {
        this.$message.error("不得少于两个字符");
        return;
      }
      this.loadBrand(query);
    },
    brandChange(val) {
      if (val == "#") {
        this.form.brandId = "";
        this.brandVisible = true;
      }
    },
    brandClose() {
      this.brandVisible = false;
    },
    brandAddConfirm(val) {
      this.barrelOptions.push(val);
      this.form.brandId = val.id;
      this.brandVisible = false;
    },
    loadSupp(query) {
      const params = new URLSearchParams();
      params.append("pageNum", 1);
      params.append("pageSize", 10);
      params.append("name", query);
      this.suppLoading = true;
      suppList(params)
        .then((response) => {
          console.log(response);
          this.suppLoading = false;
          this.suppOptions = response.data.data;
          this.setAddClickHeight();
        })
        .catch((error) => {
          this.suppLoading = false;
        });
    },
    suppChange(val) {
      if (val == "#") {
        this.form.supplierId = "";
        this.suppVisible = true;
      }
    },
    freightChange(val) {
      if (val == "/") {
        this.form.freightId = "";
        this.$refs.freight.dialogFormVisible = true;
      }
    },
    searchSupp(query) {
      console.log(query);
      if (query.length < 2) {
        this.$message.error("不得少于两个字符");
        return;
      }
      this.loadSupp(query);
    },
    suppClose() {
      this.suppVisible = false;
    },
    suppAddConfirm(val) {
      this.suppOptions.push(val);
      this.form.supplierId = val.id;
      this.suppVisible = false;
    },
    freightAddConfirm(val) {
      console.log(val);
    },
    addProduct() {
      this.length += 1;
      this.productList.push({
        isList: false,
        name: "",
        isClick: true,
        productCategoryId: "",
        shortName: "",
        orders: 0,
        isFirst: false,
        length: this.length,
        publishType: 0,
        type: "0",
        isCount: this.isCount,
        isMarketable: false,
        subTitle: "",
        freightId: "",
        minLimit: "",
        maxLimit: "",
        // labal: '',
        quality: "",
        shippingMethod: "",
        distributionId: "",
        brandId: "",
        stock: "",
        supplierId: "",
        allocatedStock: "",
        weight: "",
        subType: 0,
        // -----
        sn: this.productList[0].sn,
        thumbnail: this.productList[0].thumbnail,
        spec1: this.productList[0].spec1,
        spec2: this.productList[0].spec2,
        unit: this.productList[0].unit,
        // unitRate: this.productList[0].unitRate,
        unitRate:1,
        marketPrice: this.productList[0].marketPrice,
        price: this.productList[0].price,
        cost: this.productList[0].cost,
        unitType: 0,
        vip1price: this.productList[0].vip1price,
        vip2price: this.productList[0].vip2price,
        vip3price: this.productList[0].vip3price,
        vip4price: this.productList[0].vip4price,
        vip5price: this.productList[0].vip5price,
        isChose: false,
        point: this.productList[0].point,
        article: {
          productMeta: {
            // label: '',
            props: [{ name: "", memo: "", params: "" }],
            images: [],
            video: "",
          },
          content: "",
        },
      });
      if (this.productList.length > 1 && this.productList[0].unitType === 1) {
        for (var l = 1; l < this.productList.length; l++) {
          if (this.productList[l].unitType === 2) {
            this.productList[this.length].isCount = true;
          }
        }
      }
      if (this.productList.length > 1) {
        if (this.productList[0].unitType === 0) {
          for (var i = 1; i < this.productList.length; i++) {
            this.productList[i].unitType = 0;
            this.productList[i].isChose = true;
          }
        }
      }
      this.setAddClickHeight();
    },
    addProps() {
      var form = {
        name: "",
        memo: "",
        params: "",
      };
      this.article.productMeta.props.push(form);
      // this.setAddPropskHeight()
    },
    delProps(scope) {
      this.article.productMeta.props.splice(scope.$index, 1);
    },
    delProduct(row) {
      var index = this.productList.indexOf(row);
      if (index !== -1) {
        this.productList.splice(index, 1);
      }
      this.length -= 1;
      this.setAddClickHeight();
    },
    saveProduct(form) {
      const _this = this;
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 校验表单
          _this.clicked = true;
          const params = new URLSearchParams();
          _this.tagIds.forEach(function (item) {
            params.append("tagIds", item);
          });
          if (
            this.productList[0].unitType != 0 &&
            this.productList.length == 1
          ) {
            _this.$message({
              message: "已启用多单位，商品规格不足",
              type: "error",
            });
            _this.clicked = false;
            return;
          }

          for (var i = 0; i < _this.productList.length; i++) {
            delete this.productList[i].length;
            if (this.productList[i].hasOwnProperty("isFirst")) {
              delete this.productList[i].isFirst;
            }
            if (this.productList[i].hasOwnProperty("isChose")) {
              delete this.productList[i].isChose;
            }
            if (this.productList[i].hasOwnProperty("isCount")) {
              delete this.productList[i].isCount;
            }
            if (this.productList[i].hasOwnProperty("isClick")) {
              delete this.productList[i].isClick;
            }
            console.log(delete _this.productList[i].isClick);
            _this.productList[i].name = _this.form.name;
            _this.productList[i].productCategoryId =
              _this.form.productCategoryId;
            _this.productList[i].shortName = _this.form.shortName;
            _this.productList[i].orders = _this.form.orders;
            // _this.productList[i].type = _this.form.type;
            _this.productList[i].type = this.tempType;
            // _this.productList[i].type = this.tempType[0] - 10
            // if (this.tempType[0] - 10 == 2){
            //   _this.productList[i].subType == 0
            // } else {
            //   _this.productList[i].subType = this.tempType[1] - 20
            // }

            _this.productList[i].publishType = _this.form.publishType;
            _this.productList[i].isMarketable = _this.form.isMarketable;
            _this.productList[i].subTitle = _this.form.subTitle;
            _this.productList[i].minLimit = _this.form.minLimit;
            _this.productList[i].maxLimit = _this.form.maxLimit;
            _this.productList[i].quality = _this.form.quality;
            _this.productList[i].distributionId = _this.form.distributionId;
            _this.productList[i].brandId = _this.form.brandId;
            _this.productList[i].supplierId = _this.form.supplierId;
            _this.productList[i].allocatedStock = _this.form.allocatedStock;
            _this.productList[i].weight = _this.form.weight;
            _this.productList[i].article.productMeta =
              _this.article.productMeta;
            _this.productList[i].article.content = _this.article.content;
            _this.productList[i].freightId = _this.form.freightId;
            _this.productList[
              i
            ].shippingMethod = _this.form.shippingMethod.toString();
            if (
              parseInt(_this.productList[i].minLimit) != 0 &&
              parseInt(_this.productList[i].maxLimit) != 0 &&
              parseInt(_this.productList[i].minLimit) >
                parseInt(_this.productList[i].maxLimit)
            ) {
              _this.$message({
                message: "最小订购量不可大于每日限量",
                type: "success",
              });

              _this.clicked = false;
              return;
            }
            if (_this.productList[i].sn == "") {
              _this.$message({
                message: "请完善货号/条码",
                type: "error",
              });
              _this.clicked = false;
              return;
            }

            if (utils.isNull(_this.productList[i].unit)) {
              _this.productList[i].unit = "件";
            }
            if (utils.isNull(_this.productList[i].unitRate)) {
              _this.productList[i].unitRate = 1;
            }
            if (utils.isNull(_this.productList[i].thumbnail)) {
              _this.productList[i].thumbnail =
                "http://cdn.rzico.com/weex/resources/images/defaultProduct.png";
            }
            if (utils.isNull(_this.productList[i].weight)) {
              _this.productList[i].weight = 0;
            }
            if (utils.isNull(_this.productList[i].allocatedStock)) {
              _this.productList[i].allocatedStock = 0;
            }
            if (utils.isNull(_this.productList[i].stock)) {
              _this.productList[i].stock = 0;
            }
            if (utils.isNull(_this.productList[i].quality)) {
              _this.productList[i].quality = 0;
            }
            if (
              utils.isNull(_this.productList[i].minLimit) ||
              _this.productList[i].minLimit < 1
            ) {
              _this.productList[i].minLimit = 1;
            }
            if (utils.isNull(_this.productList[i].marketPrice)) {
              _this.productList[i].marketPrice = 0;
            }
            if (utils.isNull(_this.productList[i].price)) {
              _this.productList[i].price = 0;
            }
            if (utils.isNull(_this.productList[i].stock)) {
              _this.productList[i].stock = 0;
            }
            if (utils.isNull(_this.productList[i].cost)) {
              _this.productList[i].cost = 0;
            }
            if (utils.isNull(_this.productList[i].vip1price)) {
              _this.productList[i].vip1price = 0;
            }
            if (utils.isNull(_this.productList[i].vip2price)) {
              _this.productList[i].vip2price = 0;
            }
            if (utils.isNull(_this.productList[i].vip3price)) {
              _this.productList[i].vip3price = 0;
            }
            if (utils.isNull(_this.productList[i].vip4price)) {
              _this.productList[i].vip4price = 0;
            }
            if (utils.isNull(_this.productList[i].vip5price)) {
              _this.productList[i].vip5price = 0;
            }
            if (utils.isNull(_this.productList[i].point)) {
              _this.productList[i].point = 0;
            }
          }

          save(_this.productList, params)
            .then((response) => {
              console.log(response);
              _this.clicked = false;
              console.log(_this.type);
              if (!utils.isNull(_this.type)) {
                this.$emit("saveProduct", response.data[0]);
              } else {
                EventBus.$emit("product-add", response.data[0]);
                _this.$store
                  .dispatch("tagsView/delView", _this.$route)
                  .then(({ visitedViews }) => {
                    _this.$router.push({
                      path: "/product/list",
                    });
                  }); // 关闭当前tab回到列表
              }
            })
            .catch((error) => {
              _this.clicked = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    setAddClickHeight() {
      setTimeout(() => {
        // 获取表头的高度
        const tableTopHeight = document.querySelector(
          ".el-table__header-wrapper"
        ).offsetHeight;
        // 获取一行表格高度
        const tableHeight = document.querySelector(".el-table__row")
          .offsetHeight;
        // 获取添加按钮样式
        const addClickStyle = document.querySelector(".el-icon-plus");
        // 获取添加按钮高度
        const addClickHeight = addClickStyle.offsetHeight;
        // 设置添加按钮的位置
        const moveHeight =
          tableTopHeight +
          (this.productList.length - 1) * tableHeight +
          (tableHeight - addClickHeight) / 2;

        addClickStyle.style.top = moveHeight + "px";
      }, 100);
    },
  },
};
</script>
